<template>
  <div class="box">
    <div class="head-search">
      <search @onSubmit="onSearch">
        <el-form-item>
          <el-input placeholder="请输入内容" clearable v-model="info.val" size="small" class="input-with-select">
            <el-select v-model="info.select" clearable slot="prepend" placeholder="请选择">
              <el-option label="用户名" value="userName"></el-option>
              <el-option label="用户昵称" value="nickName"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
      </search>
      <el-button size="small" icon="el-icon-refresh" @click="handleReset">重置</el-button>
    </div>

    <div class="fun-btn">
      <el-button type="primary"
                 size="small"
                 icon="el-icon-circle-plus-outline"
                 @click="handleAddEdit('add')">新增
      </el-button>
      <el-button type="danger" plain size="small" icon="el-icon-delete" @click="handleDel('batch')">删除</el-button>
      <el-button plain size="small" @click="handleResetPsd" icon="el-icon-refresh">密码重置</el-button>
    </div>

    <section class="list-box">
      <el-table
        :data="tableData.list || []"
        border
        v-loading="loading"
        height="calc(100vh - 235px)"
        @selection-change="handleSelectionChange"
        ref="table"
        class="table">
        <el-table-column
          align="center"
          type="selection"
          fixed="left"
          width="60">
        </el-table-column>
        <el-table-column
          align="center"
          type="index"
          label="序号"
          width="60">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="userName"
          label="用户名"
          width="150">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="nickName"
          label="用户昵称"
          width="150">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="orgName"
          label="所属部门"
          width="200">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="phone"
          label="电话"
          width="150">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="remark"
          label="备注"
          width="300">
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="240">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" @click="handleAddEdit('see', scope.row)">查看</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleAddEdit('edit', scope.row)">编辑</el-button>
            <el-dropdown class="" trigger="click" @command="handleCommand($event, scope.row)">
              <span class="el-dropdown-link">
                权限管理<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="分配角色">分配角色</el-dropdown-item>
                <el-dropdown-item command="菜单权限">菜单权限</el-dropdown-item>
                <el-dropdown-item command="数据权限">数据权限</el-dropdown-item>
                <el-dropdown-item command="门类权限">门类权限</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchData.pageNo"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="searchData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total">
      </el-pagination>
    </section>

    <el-drawer
      :title="setDrawer.title"
      :size="setDrawer.size"
      :direction="setDrawer.direction"
      :visible.sync="drawer"
    >
      <assign-roles :dataList="dataList"
                    :value="value"
                    @handleSetTransfer="handleSetTransfer"
                    v-if="setDrawer.title === '分配角色'">
      </assign-roles>
      <menu-permissions :treeList="menuTreeList"
                        :checkedArr="checkedMenuTreeArr"
                        :saveLoading="menuSaveLoading"
                        :loading="getLoading"
                        @handleMenuSubmit="handleMenuSubmit"
                        v-if="setDrawer.title === '菜单权限'"></menu-permissions>
      <data-permissions @handleSaveCategory="handleSaveCategory"
                        ref="dataPer"
                        :categoryData="categoryData"
                        :saveTreeLoading="saveTreeLoading"
                        v-if="setDrawer.title === '门类权限'"></data-permissions>

      <mechanism-permissions @handleSubmitSave="handleSubmitSave"
                             ref="dataPermiss"
                             :orgData="orgData"
                             :saveLoading="saveLoading"
                             :saveTreeLoading="saveTreeLoading"
                             v-if="setDrawer.title === '数据权限'"></mechanism-permissions>

    </el-drawer>

    <el-dialog :title="dialogTitle"
               width="70%"
               top="5vh"
               :destroy-on-close="true"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :visible.sync="dialogAddEdit"
               @close="type = 'add'">
      <div class="import-content">
        <add-edit :type="type"
                  ref="diaAdd"
                  :editData="editData"
                  @handleSuccess="handleSuccess"></add-edit>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Search from '../../../../components/search/search'
import AddEdit from '../settingComponents/user/addEdit'
import AssignRoles from '../settingComponents/user/assignRoles'
import MenuPermissions from '../settingComponents/menuPermissions'
import DataPermissions from '../settingComponents/dataPermissions'

import {
  delUser, editMenuSeted, getMenuSeted,
  getUserList,
  resetPsdUser, saveUserCategoryJurisdiction, saveUserMechanismJurisdiction,
  transferAddRole, transferDelRole,
  transferRole,
  transferRoled
} from '../../../../api/user/userSet'
import { getMenuJurisdiction } from '../../../../api/menu/menuLeftNav'
import { getUserJurisdiction } from '../../../../api/dataJurisdiction'
import { getUserCategoryKeys } from '../../../../api/category/category'
import MechanismPermissions from '../settingComponents/mechanismPermissions'

export default {
  name: 'User', // 用户设置
  components: {
    MechanismPermissions,
    DataPermissions,
    MenuPermissions,
    AssignRoles,
    Search,
    AddEdit
  },
  data () {
    return {
      sex: ['女', '男', '其他'],
      drawer: false, //
      setDrawer: {
        title: '',
        size: '',
        direction: 'ltr'
      },
      value: [], // 穿梭框右边数据
      dataList: [], // 穿梭框数据
      page: {
        pageNo: 1,
        pageSize: 1000
      },
      dialogAddEdit: false,
      type: 'add',
      dialogTitle: '',
      editData: {},
      info: {
        val: '',
        select: '',
        idOrg: []
      },
      searchData: {
        pageNo: 1,
        pageSize: 20
      },
      userId: '',
      tableData: {},
      tableSelected: [],
      loading: true,
      treeProps: {
        multiple: false,
        checkStrictly: true,
        value: 'id',
        label: 'orgName'
      },
      menuTreeList: [], // 菜单权限树
      checkedMenuTreeArr: [], // 菜单权限树选中节点
      menuSaveLoading: false, // 菜单权限树提交loading
      orgData: {}, // 获取用户机构权限
      categoryData: [], // 获取用户门类权限
      saveLoading: false,
      saveTreeLoading: false,
      getLoading: false
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    getList () {
      getUserList(this.searchData).then((res) => {
        this.tableData = res.data.data
        this.loading = false
      }).catch(() => {
        this.tableData = {
          list: [],
          total: 0
        }
        this.loading = false
      })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.loading = true
      this.searchData.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.loading = true
      this.searchData.pageNo = val
      this.getList()
    },
    handleSuccess () {
      // 新增成功
      this.handleBeforeClose()
      this.getList()
    },
    handleBeforeClose () {
      // 清空新增弹窗
      this.type = ''
      this.dialogAddEdit = false
    },
    handleReset () {
      // 重置
      this.info.val = ''
      this.info.select = ''
      this.info.idOrg = []
      this.$refs.cascader.handleClear()
    },
    onSearch () {
      // 搜索
      this.loading = true
      const params = []
      if (this.info.val && this.info.select) {
        params.push({
          op: 'like',
          name: this.info.select,
          value: this.info.val
        })
      } else if (this.info.idOrg.length > 0) {
        params.push({
          op: 'eq',
          name: 'id_org',
          value: this.info.idOrg[this.info.idOrg.length - 1]
        })
      }
      this.searchData.pageSize = 20
      this.searchData.pageNo = 1
      if (params.length > 0) {
        this.searchData.params = params
      } else {
        delete this.searchData.params
      }
      this.getList()
    },
    handleAddEdit (type, row) {
      this.type = ''
      const title = {
        add: '新增',
        edit: '修改',
        see: '查看'
      }
      this.type = type
      this.dialogTitle = title[type]
      this.dialogAddEdit = true
      this.editData = row || {}
    },
    handleSelectionChange (selection) {
      // 勾选表格行
      this.tableSelected = selection
    },
    handleDel () {
      if (this.tableSelected.length > 0) {
        this.$confirm('此操作将永久删除选中的用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = []
          this.tableSelected.map((item) => {
            ids.push(item.id)
          })
          delUser(ids).then(res => {
            this.loading = true
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        }).catch(() => {
        })
      } else {
        this.$message.error('请最少选择一条信息删除！')
      }
    },
    handleResetPsd () {
      // 重置密码
      if (this.tableSelected.length > 0) {
        this.$confirm('确定将选择账号密码重置为123456?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = []
          this.tableSelected.map((item) => {
            ids.push(item.id)
          })
          resetPsdUser({
            ids,
            password: '123456'
          }).then(res => {
            this.$message({
              type: 'success',
              message: '重置密码成功!'
            })
            this.$refs.table.clearSelection()
          })
        }).catch(() => {
        })
      } else {
        this.$message.error('请最少选择一条信息进行操作！')
      }
    },
    handleCommand (command, row) {
      this.userId = row.id
      if (command === '分配角色') {
        this.value = []
        this.dataList = []
        transferRole(this.userId, this.page).then(res => {
          transferRoled(this.userId, this.page).then(resd => {
            resd.data.data.records.map(item => {
              this.value.push(item.id)
            })
            this.dataList = res.data.data.records.concat(resd.data.data.records)
          })
        })
      } else if (command === '菜单权限') {
        this.getLoading = true
        getMenuJurisdiction(this.page).then(res => {
          getMenuSeted(this.userId, []).then(resd => {
            this.checkedMenuTreeArr = resd.data.data.menuIds
            const arr = res.data.data.list || []
            this.menuTreeList = []
            arr.map(item => {
              if (item !== 'null') {
                this.menuTreeList.push(item)
              }
            })
            this.getLoading = false
          }).catch(() => {
            this.getLoading = false
          })
        })
      } else if (command === '门类权限') {
        getUserCategoryKeys(this.userId).then(res => {
          const arr = res.data.data || []
          this.categoryData = []
          arr.map(item => {
            if (item !== 'null') {
              this.categoryData.push(item)
            }
          })
        })
      } else if (command === '数据权限') {
        getUserJurisdiction(this.userId).then(res => {
          this.orgData = res.data.data || {}
        })
      }
      this.handleDrawer(command)
    },
    handleSetTransfer (val) {
      // 设置穿梭框值
      if (val.direction === 'right') {
        transferAddRole(this.userId, val.ids).then(() => {
          this.$message.success('设置成功')
        })
      } else if (val.direction === 'left') {
        transferDelRole(this.userId, val.ids).then(() => {
          this.$message.success('设置成功')
        })
      }
    },
    handleMenuSubmit (keys) {
      // 菜单权限设置提交
      this.menuSaveLoading = true
      editMenuSeted(this.userId, { ids: keys }).then(res => {
        this.menuSaveLoading = false
        this.drawer = false
        this.$message.success('设置成功！')
      }).catch(() => {
        this.menuSaveLoading = false
      })
    },
    handleSubmitSave (val) {
      // 机构权限范围设置
      if (this.orgData.id) {
        val.id = this.orgData.id
      }
      val.idData = this.userId
      val.dataType = 'user'
      this.saveLoading = true
      saveUserMechanismJurisdiction(val).then(res => {
        this.$message.success('设置成功')
        this.saveLoading = false
        this.drawer = false
      }).catch(() => {
        this.saveLoading = false
      })
    },
    handleSaveCategory (val) {
      // 门类数据权限范围设置
      val.idData = this.userId
      this.saveTreeLoading = true
      saveUserCategoryJurisdiction(val).then(res => {
        this.$message.success('设置成功')
        this.saveTreeLoading = false
        this.drawer = false
      }).catch(() => {
        this.saveTreeLoading = false
      })
    },
    handleDrawer (type) {
      const arr = [{
        title: '分配角色',
        size: '60%',
        direction: 'rtl'
      }, {
        title: '菜单权限',
        size: '80%',
        direction: 'rtl'
      }, {
        title: '数据权限',
        size: '500px',
        direction: 'rtl'
      }, {
        title: '门类权限',
        size: '300px',
        direction: 'rtl'
      }]
      this.drawer = true
      arr.map(item => {
        if (item.title === type) {
          this.setDrawer = item
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .box {
    .head-search {
      .bumen {
        position: relative;
        top: -4px;
      }

      ::v-deep input {
        height: 32px !important;
      }
    }

    .el-dropdown-link {
      margin-left: 10px;
      color: #409EFF;
      cursor: pointer;
    }
  }
</style>
